import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Store } from '@ngxs/store';
import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AuthService } from '../../shared/auth/auth.service';
import { Navigate } from '@ngxs/router-plugin';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss'],
})
export class RegisterComponent implements OnInit {
  registerForm: FormGroup;

  constructor(
      private message: NzMessageService,
      private store: Store,
      private fb: FormBuilder,
      private auth: AuthService,
  ) {
    this.registerForm = this.fb.group({
      username: ['', Validators.required],
      password: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      confirm: ['', [Validators.required, this.checkConfirm()]],
    });
  }

  ngOnInit(): void {
  }

  submit() {
    let param = this.registerForm.getRawValue();
    delete param.confirm;
    this.auth.register(param).subscribe({
      next: () => {
        this.message.success(`注册成功`);
        this.store.dispatch(new Navigate(['/login']));
      },
      error: (e) => {
        if (!!e.error.message) {
          this.message.error(`${e.error.message}`);
        } else {
          this.message.error(`注册失败`);
        }
      },
    });
  }

  checkConfirm() {
    return (control: AbstractControl) => {
      return !!control.value && control.value === this.registerForm.get('password')?.getRawValue()
          ? null : {confirmError: true};
    };
  }
}
